import { IMainMenu } from '@/models/IMainMenu';
import { HttpClient } from './HttpClient';
import { Session } from './Session';
import { WebVariable } from './WebVariable';
import { Api } from './Api';
import { IResponse } from '@/models/IResponse';
import { UI } from '@/utils/UI';
import { request } from '@zny/utils';

/**主菜单服务 */
export class MainMenuService {

    /**
     * 从服务器获取主菜单
     * @param isPortal 是否是门户菜单
     */
    static getMainMenu(isPortal: boolean = false): Promise<IMainMenu[]> {
        const client = new HttpClient()
        client.removeProjectId = isPortal
        const user = Session.getUser()
        console.log("user uuuu:", user)
        return new Promise((resolve, reject) => {
            client.get(`/api/usm/SysAction/GetActionByUserId?sysId=${WebVariable.sysId}&userId=${user?.id ?? ""}`).then(res => {
                Api.processResponse<IResponse<IMainMenu[]>>(res).then(data => {
                    if (data?.success) {
                        // 数据重组，增加url的地址
                        this.getAllMenuPath().then((res) => {
                            let menuList = this.getChildMenuList(this.listToTree(data.data), res);
                            const projectNameList=menuList.find((t: { name: string; })=>t.name=="项目");
                            if(typeof projectNameList=="undefined"){
                                menuList.push({
                                    "id": "074EF0FE-D817-9C08-AB11-C4E3E33AD9C2",
                                    "parentId": null,
                                    "level": 1,
                                    "hasChildren": true,
                                    "fullPath": "项目",
                                    "name": "项目",
                                    "sysId": "218FC712-F776-9170-FFD5-219157BFA3D7",
                                    "children": [{
                                        "id": "27882461-A9BC-633D-FC4D-A681BF72E480",
                                        "parentId": "074EF0FE-D817-9C08-AB11-C4E3E33AD9C2",
                                        "level": 2,
                                        "hasChildren": false,
                                        "fullPath": "项目/项目列表",
                                        "name": "项目列表",
                                        "expanded": false,
                                        "isHide": false,
                                        "sysId": "218FC712-F776-9170-FFD5-219157BFA3D7",
                                        "url": "/biz-portals/project/Projects",
                                        "pageId": "",
                                        "children": [],
                                        "externalUrl": ""
                                    }],
                                    "externalUrl": ""
                                });
                            }
                            resolve(menuList ?? [])
                        });
                    } else {
                        UI.errorNotification(data?.message ?? "API 错误")
                        reject()
                    }
                })
            })
        })
    }

    /**获取门户一级菜单名 */
    static getPortalTopLevelMenus(menus: IMainMenu[]) {
        const menuNames = WebVariable.PORTAL_MENU_NAMES
        return menus.filter(m => (m.parentId?.length ?? 0) < 1
            && menuNames.indexOf(m.name ?? "") > -1)
    }


    /**获取菜单对应的URL地址 */
    static async getAllMenuPath() {
        let pathnameMap: any = [];
        await request('/rjApi/page')
            .then(res => {
                pathnameMap = res.reduce((dict: any, item: any) => {
                    dict[item.id] = item.pathname;
                    return dict;
                }, {});
            })
            .catch(err => {
                console.log(err, 'err');
            });
        return pathnameMap;
    }

    /**重新组成树结构。 */
    static listToTree = (list: any) => {
        if (!Array.isArray(list) || list.length === 0) return list;
        var map: any = {},
            roots = [];
        for (var i = 0; i < list.length; i++) {
            map[list[i].id] = i;
            list[i].children = [];
        }
        for (var i = 0; i < list.length; i++) {
            var node = list[i];
            if (node.parentId == null || node.parentId == 'null') {
                roots.push(node);
            } else {
                try {
                    list[map[node.parentId]].children.push(node);
                } catch (error) {
                    console.log(node, 'node.parentId');
                    console.log(error, 'error');
                }
            }
        }
        return roots;
    };


    /**数据排序 */
    static compare = (prop: any) => {
        return function (a: any, b: any) {
            return b[prop] - a[prop];
        };
    };

    /**菜单重组 */
    static getChildMenuList = (menuList: any, pathnameMap: any) => {
        menuList = menuList.sort(MainMenuService.compare('orderIndex'));
        Object.keys(menuList).forEach((key: any) => {
            menuList[key].url =
                menuList[key].url ||
                (!menuList[key].menuOpenType ? pathnameMap[menuList[key].pageId] : '') ||
                '';
            menuList[key].externalUrl = menuList[key].menuOpenType == 'ExternalUrl' ? menuList[key].url : '';
            if (menuList[key]['children'].length > 0) {
                MainMenuService.getChildMenuList(menuList[key]['children'], pathnameMap);
            }
        });
        return menuList;
    };

    private static parents: IMainMenu[] = []
    /**
     * 通过菜单ID获取菜单层级集合
     * @param menuUrl 菜单ID
     * @param menus 数据源
     */
    static getLeveledMenus(menuUrl: string | undefined, menus: IMainMenu[]): IMainMenu[] {
        if (typeof menuUrl === "undefined") {
            return []
        }
        for (let item of menus) {
            this.parents.length = 0
            if (this.findInArray(menuUrl, item)) {
                return this.parents.reverse()
            }
        }
        return []
    }

    private static findInArray(menuUrl: string, menuItem: IMainMenu): boolean {
        if (menuUrl === menuItem.url) {
            this.parents.push(menuItem)
            return true
        }
        for (let c of menuItem.children ?? []) {
            if (this.findInArray(menuUrl, c)) {
                this.parents.push(menuItem)
                return true
            }
        }
        return false
    }

}